# -*- coding:utf-8 -*-
'''
@author: xiaoming
@contact: lishihui0129@163.com
@time: 2017/6/29 15:40
@desc:
'''
import re
import os
from myUtil import mobilphonePattern,flagSplitPattern
from mysqlHelper import connectDB,close,insertSql


def mobelphoneNumberExtract(string):
    '''
    :param string: 待提取对象
    :return:提取结果
    '''
    res=re.findall(mobilphonePattern,string)

    res=list(set(res))
    # flag=prefixFlag(string)

    temp=[]

    for item in res:
        linshi=item.strip()
        # linshi="手机:"+item+"("+flag.strip()+")"
        temp.append(linshi)
    # return ";".join(temp)
    return temp


def prefixFlag(string):
    '''
    :param string: 待提取对象
    :return:前缀信息
    '''
    linshi=string
    string=string.lower()
    string=string.replace(" ","").replace("　","")
    if '手机' in string:
        ind=string.index('手机')
    elif '移动电话' in string:
        ind=string.index('移动电话')
    elif '行动电话' in string:
        ind=string.index('行动电话')
    elif '热线' in string:
        ind=string.index('热线')
    elif '专线' in string:
        ind=string.index('专线')
    elif 'cel' in string:
        ind=string.index('cel')
    elif 'mob' in string:
        ind=string.index('mob')
    elif 'mobile' in string:
        ind=string.index('mobile')
    else:
        ind=0
    temp=string[:ind]
    # print linshi
    # print temp
    res=re.split(flagSplitPattern,temp)
    # print res[-1]
    jieguo=res[-1].strip()


    if len(jieguo)>12:
        return ""
    else:
        return res[-1].strip()

def insertPhoneTable(string):
    res=re.findall(mobilphonePattern,string)
    res=list(set(res))
    flag=prefixFlag(string)
    connectDB()
    sql="insert into mobilphone(phone_value,prefix) values(%s,%s)"

    for each in res:
        param=(each,flag)
        insertSql(sql,param)
    close()


if __name__=='__main__':
    workdir='.\output'
    fileList=os.listdir(workdir)
    if 'phone.txt' in fileList:
        targetFile=os.path.join(workdir,'phone.txt')
        res=open(targetFile).readlines()
        for line in res:
            if len(line.strip())!=0:
                print mobelphoneNumberExtract(line)
                insertPhoneTable(line)
            else:
                continue
    else:
        pass